﻿using System;
using System.Data;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using Infragistics.WebUI.UltraWebGrid;
using uMES.LeanManufacturing.ReportBusiness;
using uMES.LeanManufacturing.ParameterDTO;
using System.Drawing;
using System.Configuration;
using System.Web.UI;
using uMES.LeanManufacturing.DBUtility;
public partial class WorkReportForm : ShopfloorPage
{
    const string QueryWhere = "WorkReportForm";
    uMESCommonBusiness common = new uMESCommonBusiness();
    uMESDispatchBusiness dispatch = new uMESDispatchBusiness();
    uMESWorkReportBusiness workreport = new uMESWorkReportBusiness();
    uMESMaterialBusiness material = new uMESMaterialBusiness();
    int m_PageSize = 9;
    string businessName = "报工管理", parentName = "workreportinfo";
    protected void Page_Load(object sender, EventArgs e)
    {
        uMESMasterPage master = this.Master as uMESMasterPage;
        master.strNavigation = "当前位置：报工管理";
        master.strTitle = "报工管理";
        master.ChangeFrame(true);
        NormalReportControl normalCntrl = new NormalReportControl();
     
        WebPanel = WebAsyncRefreshPanel1;
        upageTurning.PageIndexChanged += new pageTurning.PageIndexChangedEventHandler(() => { QueryData(upageTurning.CurrentPageIndex); });

        if (!IsPostBack)
        {
            ClearMessage_PageLoad();
            GetMutualChecker();
            GetResource();
            GetEmployee();
        }
    }

    #region 获取互检人
    protected void GetMutualChecker()
    {
        Dictionary<string, string> userInfo = Session["UserInfo"] as Dictionary<string, string>;
        string strFactoryID = userInfo["FactoryID"];
        string strEmployeeID = userInfo["EmployeeID"];
        string strTeamID = userInfo["TeamID"];
        DataTable DT = workreport.GetMutualChecker(strFactoryID, strEmployeeID, strTeamID);

        ddlMutualChecker.DataTextField = "FullName";
        ddlMutualChecker.DataValueField = "EmployeeID";
        ddlMutualChecker.DataSource = DT;
        ddlMutualChecker.DataBind();

        ddlMutualChecker.Items.Insert(0, "");
    }
    #endregion

    #region 获取资源列表
    protected void GetResource()
    {
        Dictionary<string, string> userInfo = Session["UserInfo"] as Dictionary<string, string>;
        string strFactoryID = userInfo["FactoryID"];
        string strTeamID = userInfo["TeamID"];
        DataTable DT = common.GetResource(strFactoryID, strTeamID);

        ddlResource.DataTextField = "ResourceName";
        ddlResource.DataValueField = "ResourceID";
        ddlResource.DataSource = DT;
        ddlResource.DataBind();

        ddlResource.Items.Insert(0, "");
    }
    #endregion

    #region 获取人员列表
    protected void GetEmployee()
    {
        Dictionary<string, string> userInfo = Session["UserInfo"] as Dictionary<string, string>;
        string strTeamID = userInfo["TeamID"];
        DataTable DT = common.GetEmployee(strTeamID);

        wgEmployee.DataSource = DT;
        wgEmployee.DataBind();
    }
    #endregion

    #region 数据查询

    #region 重置
    protected void btnReSet_Click(object sender, EventArgs e)
    {
        hdScanCon.Value = string.Empty;
        upageTurning.TotalRowCount = 0;
        ResetQuery();
        ClearDispData();
    }
    #endregion
    public Dictionary<string, string> GetQuery()
    {
        string strScanContainerName = txtScan.Text.Trim();
        string strProcessNo = txtProcessNo.Text.Trim();
        string strContainerName = txtContainerName.Text.Trim();
        string strProductName = txtProductName.Text.Trim();
        string strSpecName = txtSpecName.Text.Trim();
        string strStartDate = txtStartDate.Value.Trim();
        string strEndDate = txtEndDate.Value.Trim();

        Dictionary<string, string> result = new Dictionary<string, string>();
        Dictionary<string, string> userInfo = Session["UserInfo"] as Dictionary<string, string>;
        string strTeamID = userInfo["TeamID"];
        result.Add("TeamID", strTeamID);
        result.Add("DispatchType", "1");
        if (!string.IsNullOrEmpty(hdScanCon.Value))
        {
            result.Add("ScanContainerName", hdScanCon.Value);
        }
        else
        {
            result.Add("ProcessNo", strProcessNo);
            result.Add("ContainerName", strContainerName);
            result.Add("ProductName", strProductName);
            result.Add("SpecName", strSpecName);
            result.Add("StartDate", strStartDate);
            result.Add("EndDate", strEndDate);
        }
        result.Add("ReportEmployeeID", userInfo["EmployeeID"]);//派工所选定的人，都能报

        return result;
    }

    public void QueryData(int intIndex)
    {
        ClearMessage();

        uMESPagingDataDTO result = workreport.GetSourceData(GetQuery(), intIndex, m_PageSize);
        this.ItemGrid.DataSource = result.DBTable;
        this.ItemGrid.DataBind();
        //给分页控件赋值，用于分页控件信息显示
        this.upageTurning.TotalRowCount = int.Parse(result.RowCount);
        this.upageTurning.RowCountByPage = m_PageSize;
        ClearDispData();
    }

    protected void ItemGrid_DataBound(object sender, EventArgs e)
    {
        for (int i = 0; i < ItemGrid.Rows.Count; i++)
        {
            string strSpecName = ItemGrid.Rows[i].Cells.FromKey("SpecName").Value.ToString();
            ItemGrid.Rows[i].Cells.FromKey("SpecNameDisp").Text = common.GetSpecNameWithOutProdName(strSpecName);
        }
    }

    public void ResetQuery()
    {
        ClearMessage();

        Session[QueryWhere] = "";
        txtScan.Text = string.Empty;
        txtProcessNo.Text = string.Empty;
        txtContainerName.Text = string.Empty;
        txtProductName.Text = string.Empty;
        txtSpecName.Text = string.Empty;
        txtStartDate.Value = string.Empty;
        txtEndDate.Value = string.Empty;
        ItemGrid.Rows.Clear();
    }
    #endregion

    
    #region 选中批次行
    protected void ItemGrid_ActiveRowChange(object sender, RowEventArgs e)
    {
        ClearMessage();
        tdproductNo.Style.Add("display", "none");
        try
        {
            txtDispProcessNo.Text = string.Empty;
            if(e.Row.Cells.FromKey("ProcessNo").Value!=null)
            { 
                string strProcessNo = e.Row.Cells.FromKey("ProcessNo").Value.ToString();
                txtDispProcessNo.Text = strProcessNo;
            }

            txtDispOprNo.Text = string.Empty;
            if (e.Row.Cells.FromKey("OprNo").Value != null)
            {
                string strOprNo = e.Row.Cells.FromKey("OprNo").Value.ToString();
                txtDispOprNo.Text = strOprNo;
            }

            string strContainerName = e.Row.Cells.FromKey("ContainerName").Value.ToString();
            txtDispContainerName.Text = strContainerName;
            string strContainerID = e.Row.Cells.FromKey("ContainerID").Value.ToString();
            txtDispContainerID.Text = strContainerID;

            string strProductName = e.Row.Cells.FromKey("ProductName").Value.ToString();
            txtDispProductName.Text = strProductName;

            txtDispDescription.Text = string.Empty;
            if (e.Row.Cells.FromKey("Description").Value != null)
            {
                string strDescription = e.Row.Cells.FromKey("Description").Value.ToString();
                txtDispDescription.Text = strDescription;
            }

            string strQty = e.Row.Cells.FromKey("Qty").Value.ToString();
            txtDispQty.Text = strQty;

            //图号ID 
            string strProductID =string.Empty;
            if (e.Row.Cells.FromKey("ProductID").Value != null)
            {
                 strProductID = e.Row.Cells.FromKey("ProductID").Value.ToString();
                txtProductID.Text = strProductID;
            }


            //批次数量 
            string strContaiernQty = string.Empty; 
            if (e.Row.Cells.FromKey("ContaiernQty").Value != null)
            {
                strContaiernQty = e.Row.Cells.FromKey("ContaiernQty").Value.ToString();
                txtContaiernQty.Text = strContaiernQty;
            }

            //计划开始时间
            string strStartTime = string.Empty;
            if (e.Row.Cells.FromKey("ContainerStartDate").Value != null)
            { 
                strStartTime = e.Row.Cells.FromKey("ContainerStartDate").Value.ToString();
                txtStartTime.Text = strStartTime;
            }


            //计划结束时间
            string strEndTime = string.Empty;
            if (e.Row.Cells.FromKey("ContainerCompletionDate").Value != null)
            {
                strEndTime = e.Row.Cells.FromKey("ContainerCompletionDate").Value.ToString();
                txtEndTime.Text = strEndTime;
            }

            //生产任务 
            string strMfgorderName = string.Empty;
            if (e.Row.Cells.FromKey("MfgorderName").Value != null)
            {
                 strMfgorderName = e.Row.Cells.FromKey("MfgorderName").Value.ToString();
                txtMfgorderName.Text = strMfgorderName;
            }


            string strSpec = e.Row.Cells.FromKey("SpecNameDisp").Value.ToString();
            txtDispSpecName.Text = strSpec;
            string strWorkflowID = e.Row.Cells.FromKey("WorkflowID").Value.ToString();
            txtDispWorkflowID.Text = strWorkflowID;
            string strSpecID = e.Row.Cells.FromKey("SpecID").Value.ToString();
            txtDispSpecID.Text = strSpecID;

            string strTeamName = e.Row.Cells.FromKey("TeamName").Value.ToString();
            txtDispTeamName.Text = strTeamName;
            string strTeamID = e.Row.Cells.FromKey("TeamID").Value.ToString();
            txtDispTeamID.Text = strTeamID;
            
            if (e.Row.Cells.FromKey("PlannedCompletionDate").Value != null)
            {
                string strPlannedCompletionDate = e.Row.Cells.FromKey("PlannedCompletionDate").Value.ToString();
                strPlannedCompletionDate = Convert.ToDateTime(strPlannedCompletionDate).ToString("yyyy-MM-dd");
                txtDispPlannedCompletionDate.Text = strPlannedCompletionDate;
            }

            string strID = e.Row.Cells.FromKey("ID").Value.ToString();
            txtDispID.Text = strID;

            DataTable dtEmployee = dispatch.GetEmployeeByDispatchID(strID);
            TemplatedColumn temCell = (TemplatedColumn)wgEmployee.Columns.FromKey("ckSelect");

            for (int i = 0; i < temCell.CellItems.Count; i++)
            {
                Infragistics.WebUI.UltraWebGrid.CellItem cellItem = (Infragistics.WebUI.UltraWebGrid.CellItem)temCell.CellItems[i];
                CheckBox ckSelect = (CheckBox)cellItem.FindControl("ckSelect");
                ckSelect.Checked = false;

                string strEmployeeID = wgEmployee.Rows[i].Cells.FromKey("EmployeeID").Value.ToString();
                //更改为默认只选择自己
                Dictionary<string, string> userInfo = Session["UserInfo"] as Dictionary<string, string>;
                if (strEmployeeID == userInfo["EmployeeID"])
                {
                    ckSelect.Checked = true;
                    break;
                }
                //foreach (DataRow row in dtEmployee.Rows)
                //{
                //    string strEID = row["EmployeeID"].ToString();
                //    if (strEID == strEmployeeID)
                //    {
                //        ckSelect.Checked = true;
                //        break;
                //    }
                //}
            }

            string strResourceID = string.Empty;
            if (e.Row.Cells.FromKey("ResourceID").Value != null)
            {
                strResourceID= e.Row.Cells.FromKey("ResourceID").Value.ToString();
                try
                {
                    ddlResource.SelectedValue = strResourceID;
                }
                catch
                {
                }
                
            }
            

            wgProductNo.Clear();
            DataTable dtProductNo = workreport.GetWillReportProductNo(strID);
            wgProductNo.DataSource = dtProductNo;
            wgProductNo.DataBind();

            txtQty.Text = string.Empty;
            txtReportedQty.Text = workreport.GetReportedQty(strID).ToString();
            if (dtProductNo.Rows.Count == 0)
            {
                txtQty.Text = (Convert.ToInt32(txtDispQty.Text) - Convert.ToInt32(txtReportedQty.Text)).ToString();
            }
            else
            {
                tdproductNo.Style.Add("display", "block");
            }
        }
        catch (Exception ex)
        {
            DisplayMessage(ex.Message, false);
        }
    }

    #endregion

    #region 保存按钮
    protected void btnSave_Click(object sender, EventArgs e)
    {
        ClearMessage();

        try
        {
            ResultModel re = SaveData();
            if (re.IsSuccess == false) {
                DisplayMessage(re.Message,false);
                return;
            }
            #region 记录日志
            Dictionary<string, string> userInfo = Session["UserInfo"] as Dictionary<string, string>;
            var ml = new MESAuditLog();
            ml.ContainerName = txtDispContainerName.Text; ml.ContainerID = txtDispContainerID.Text;
            ml.ParentID = re.Data.ToString(); ml.ParentName = parentName;
            ml.CreateEmployeeID = userInfo["EmployeeID"];
            ml.BusinessName = businessName; ml.OperationType = 0;
            ml.Description = "批次报工:" + txtDispSpecName.Text + ",报工数:"+ txtQty.Text;
            common.SaveMESAuditLog(ml);
            #endregion

            QueryData(1);
            //清空数量
            txtQty.Text = "";
            DisplayMessage("保存成功", true);
        }
        catch (Exception ex)
        {
            DisplayMessage(ex.Message, false);
        }
    }

    ResultModel SaveData() {
        ResultModel re = new ResultModel(false,"");

        string strID = txtDispID.Text;
        if (strID == string.Empty)
        {
            re.Message = "请选择要报工的派工记录";
            return re;
        }

        string strQty = string.Empty;
        DataTable dtProductNo = new DataTable();
        string strMsg;
        if (CheckData(out strQty, out dtProductNo,out strMsg) == false)
        {
            re.Message = strMsg;
            return re;
        }

        UploadFile();
        UltraGridRow activeRow = ItemGrid.DisplayLayout.ActiveRow;
        string strReportInfoName = DateTime.Now.ToString("yyyyMMddHHmmssfff");
        string strContainerID = txtDispContainerID.Text;
        string strSpecID = txtDispSpecID.Text;
        string strWorkflowID = txtDispWorkflowID.Text;
        string strtxtProductID = txtProductID.Text;
        string strTeamID = txtDispTeamID.Text;
        string strResourceID = ddlResource.SelectedValue;

        Dictionary<string, string> userInfo = Session["UserInfo"] as Dictionary<string, string>;
        string strReportEmployeeID = userInfo["EmployeeID"];

        string strReportType = "3";
        if (cbReportType.Checked == true)
        {
            strReportType = "0";
        }

        string strMutualCheckerID = ddlMutualChecker.SelectedValue;

        Dictionary<string, string> para = new Dictionary<string, string>();
        para.Add("WorkReportInfoName", strReportInfoName);
        para.Add("ContainerID", strContainerID);
        para.Add("SpecID", strSpecID);
        para.Add("Qty", strQty);
        para.Add("UOMID", "");
        para.Add("ResourceID", strResourceID);
        para.Add("ReportEmployeeID", strReportEmployeeID);
        para.Add("ReportDate", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
        para.Add("ReportType", strReportType);
        para.Add("DispatchInfoID", strID);
        para.Add("Notes", "");
        para.Add("SynergicInfoID", "");
        para.Add("WorkflowID", strWorkflowID);
        para.Add("MutualCheckerID", strMutualCheckerID);
        para.Add("WorkflowStepID", activeRow.Cells.FromKey("WorkflowStepID").Text);
        para.Add("FactoryID", userInfo["FactoryID"]);
        para.Add("WorkReportInfoID", Guid.NewGuid().ToString());

        //判断报工工序是否是下料工序，如果是则判断是否发料，未发料无法报工
        if (txtSpecName.Text.Contains("下料"))
        {
            Dictionary<string,string> paraCheck =  new Dictionary<string, string>();

            paraCheck.Add("CheckContainerName", txtDispContainerName.Text);
            paraCheck["IsSendMaterial"] = "1";
            paraCheck["CurrentPageIndex"] = "1";
            paraCheck["PageSize"] = "20";
            uMESPagingDataDTO result = material.GetErpSucceedRecevieData(para);
            if(result.DBTable.Rows.Count==0)
            re.Message = "下料工序未发料，无法进行报工操作";
            return re;
        }

        //加工人员
        DataTable dtEmployee = new DataTable();
        dtEmployee.Columns.Add("EmployeeID"); dtEmployee.Columns.Add("WorkHours");
        TemplatedColumn temCell = (TemplatedColumn)wgEmployee.Columns.FromKey("ckSelect");
        //此报工总工时
        string strunitworktime = "0";
        if (activeRow.Cells.FromKey("unitworktime").Value !=null)
        {
            strunitworktime = activeRow.Cells.FromKey("unitworktime").Text;
        }
        var isReport = OracleHelper.QueryDataByEntity(new ExcuteEntity("workreportinfo", ExcuteType.selectAll)
        {
            WhereFileds = new List<FieldEntity>() {
                new FieldEntity("WorkflowStepID",activeRow.Cells.FromKey("WorkflowStepID").Text,FieldType.Str)
            },
            strWhere = " and containerid in (select containerid from container where mfgorderid='" + activeRow.Cells.FromKey("mfgorderid").Text + "') "
        });
        string strsetupworktime = "0";
        if (isReport.Rows.Count==0&&activeRow.Cells.FromKey("setupworktime").Value!=null)
        {
            strsetupworktime = activeRow.Cells.FromKey("setupworktime").Text;
        }
        double reportAllHours = int.Parse(txtQty.Text) * Convert.ToDouble(strunitworktime) + Convert.ToDouble(strsetupworktime);
        int reportAllHours2=0;//分配的总工时
        for (int i = 0; i < temCell.CellItems.Count; i++)
        {
            Infragistics.WebUI.UltraWebGrid.CellItem cellItem = (Infragistics.WebUI.UltraWebGrid.CellItem)temCell.CellItems[i];
            CheckBox ckSelect = (CheckBox)cellItem.FindControl("ckSelect");

            if (ckSelect.Checked == true)
            {
                //
                //if (string.IsNullOrWhiteSpace(wgEmployee.Rows[i].Cells.FromKey("WorkHour").Text) == true)
                //{
                //    re.Message = "第 " + (i + 1) + " 行工时（时）不能为空";
                //    return re;
                //}
                //if (string.IsNullOrWhiteSpace(wgEmployee.Rows[i].Cells.FromKey("WorkMin").Text) == true)
                //{
                //    re.Message = "第 " + (i + 1) + " 行工时（分）不能为空";
                //    return re;
                //}
                //

                DataRow row = dtEmployee.NewRow();
                row["EmployeeID"] = wgEmployee.Rows[i].Cells.FromKey("EmployeeID").Value.ToString();
                int rowWorkHour = string.IsNullOrWhiteSpace(wgEmployee.Rows[i].Cells.FromKey("WorkHour").Text) ? 0 : Convert.ToInt32(wgEmployee.Rows[i].Cells.FromKey("WorkHour").Text);
                int rowWorkMin= string.IsNullOrWhiteSpace(wgEmployee.Rows[i].Cells.FromKey("WorkMin").Text) ? 0 : Convert.ToInt32(wgEmployee.Rows[i].Cells.FromKey("WorkMin").Text);
                row["WorkHours"] = 60 * rowWorkHour + rowWorkMin;                
                dtEmployee.Rows.Add(row);
                reportAllHours2 += int.Parse(row["WorkHours"].ToString());
            }
        }
        //判断是否含有自己
        if (dtEmployee.Select(string.Format("employeeid='{0}'",userInfo["EmployeeID"])).Length == 0)
        {
            re.Message = "必须选择自己";
            return re;
        }
        //判断自由分配的工时是否和总工时相等
        if (reportAllHours != reportAllHours2) {
            re.Message = "此次报工总工时为："+reportAllHours.ToString()+"，分配的总工时为："+reportAllHours2+"，两者不相等";
            return re;
        }

        workreport.AddWorkReportInfo(para, dtProductNo, dtEmployee);

        //更新派工单状态
        int intDispatchQty = Convert.ToInt32(txtDispQty.Text);
        int intReportedQty = Convert.ToInt32(txtReportedQty.Text);
        int intQty = Convert.ToInt32(strQty);

        if (intQty + intReportedQty >= intDispatchQty)
        {
            dispatch.ChangeDispatchStatus(strID, 40);
        }
        else
        {
            dispatch.ChangeDispatchStatus(strID, 30);
        }

        re = new ResultModel(true,"保存成功");
        re.Data = para["WorkReportInfoID"];//为记录日志所用
        return re;

    }

    #region 附件上传
    protected void UploadFile()
    {
        string strPath = ConfigurationManager.AppSettings["UploadFilePath"];
        string strFileName = fileUpload.FileName;

        if (strFileName != string.Empty)
        {
            fileUpload.PostedFile.SaveAs(strPath + fileUpload.FileName);
        }
    }
    #endregion

    protected void ClearDispData()
    {
        txtDispProcessNo.Text = string.Empty;
        txtDispOprNo.Text = string.Empty;
        txtDispContainerName.Text = string.Empty;
        txtDispProductName.Text = string.Empty;
        txtDispDescription.Text = string.Empty;
        txtDispQty.Text = string.Empty;
        txtDispSpecName.Text = string.Empty;
        txtDispTeamName.Text = string.Empty;
        txtDispPlannedCompletionDate.Text = string.Empty;
        txtReportedQty.Text = string.Empty;
        txtContaiernQty.Text = string.Empty;
        txtDispWorkflowID.Text = string.Empty;
        txtProductID.Text = string.Empty;
        txtStartTime.Text = string.Empty;
        txtEndTime.Text = string.Empty;

        txtDispID.Text = string.Empty;
        ddlResource.SelectedValue = string.Empty;
        txtQty.Text = string.Empty;
        ddlMutualChecker.SelectedValue = string.Empty;
        txtNotes.Text = string.Empty;
        cbReportType.Checked = false;

        wgProductNo.Clear();

        TemplatedColumn temCell = (TemplatedColumn)wgEmployee.Columns.FromKey("ckSelect");

        for (int i = 0; i < temCell.CellItems.Count; i++)
        {
            Infragistics.WebUI.UltraWebGrid.CellItem cellItem = (Infragistics.WebUI.UltraWebGrid.CellItem)temCell.CellItems[i];
            CheckBox ckSelect = (CheckBox)cellItem.FindControl("ckSelect");

            ckSelect.Checked = false;
            wgEmployee.Rows[i].Cells.FromKey("WorkHour").Value = "";
            wgEmployee.Rows[i].Cells.FromKey("WorkMin").Value = "";
        }
    }

    #region 数据验证
    protected Boolean CheckData(out string strDipatchQty, out DataTable dtProductNo,out string strMessage)
    {
        Boolean result = true; strMessage = "";

        string strResourceID = ddlResource.SelectedValue;

        if (strResourceID == "")
        {
            //DisplayMessage("请选择设备/工位", false);
            //ddlResource.Focus();
            //result = false;
        }

        int intQty = 0;
        DataTable DT = new DataTable();
        DT.Columns.Add("ContainerID");
        DT.Columns.Add("ContainerName");
        DT.Columns.Add("ProductNo");

        if (wgProductNo.Rows.Count > 0)
        {
            TemplatedColumn temCell = (TemplatedColumn)wgProductNo.Columns.FromKey("ckSelect");

            for (int i = 0; i < temCell.CellItems.Count; i++)
            {
                Infragistics.WebUI.UltraWebGrid.CellItem cellItem = (Infragistics.WebUI.UltraWebGrid.CellItem)temCell.CellItems[i];
                CheckBox ckSelect = (CheckBox)cellItem.FindControl("ckSelect");

                if (ckSelect.Checked == true)
                {
                    intQty++;

                    DataRow row = DT.NewRow();
                    row["ContainerID"] = wgProductNo.Rows[i].Cells.FromKey("ContainerID").Value.ToString();
                    row["ContainerName"] = wgProductNo.Rows[i].Cells.FromKey("ContainerName").Value.ToString();
                    row["ProductNo"] = wgProductNo.Rows[i].Cells.FromKey("ProductNo").Value.ToString();
                    DT.Rows.Add(row);
                }
            }

            if (intQty == 0)
            {
                strMessage = "请勾选产品序号";
                //DisplayMessage("请勾选产品序号", false);
                result = false;
            }
        }
        else
        {
            string strQty = txtQty.Text.Trim();

            if (strQty == string.Empty)
            {
                strMessage = "请输入数量";
                txtQty.Focus();
                result = false;
            }
            else
            {
                if (strQty.Contains("."))
                {
                    strMessage = "数量应为正数";
                    txtQty.Focus();
                    result = false;
                }
                else
                {
                    try
                    {
                        intQty = Convert.ToInt32(strQty);

                        if (intQty <= 0)
                        {
                            strMessage = "数量应为正整数";
                            txtQty.Focus();
                            result = false;
                        }
                    }
                    catch
                    {
                        strMessage = "数量应为数字";
                        txtQty.Focus();
                        result = false;
                    }
                }
            }
        }

        if (cbReportType.Checked == true && intQty > 1)
        {
            strMessage = "首件报工数量不能大于1";
            result = false;
        }

        if (intQty + Convert.ToInt32(txtReportedQty.Text) > Convert.ToInt32(txtDispQty.Text))
        {
            strMessage = "总数量不能大于派工数量";
            txtQty.Focus();
            result = false;
        }

        strDipatchQty = intQty.ToString();

        string strFileName = fileUpload.FileName;
        string strPath = ConfigurationManager.AppSettings["UploadFilePath"];

        if(System.IO.File.Exists(strPath + strFileName))
        {
            strMessage = "附件已存在,请更换附件或修改文件名";
            result = false;
        }
        
        dtProductNo = DT.Copy();
        return result;
    }
    #endregion

    #endregion

    protected void txtScan_TextChanged(object sender, EventArgs e)
    {
        ClearMessage();

        try
        {
            string strScan = txtScan.Text.Trim();
            txtScan.Text = "";
            hdScanCon.Value = string.Empty;
            if (strScan != string.Empty)
            {

                hdScanCon.Value = strScan;
                QueryData(1);
            }
        }
        catch (Exception ex)
        {
            DisplayMessage(ex.Message, false);
        }
    }

    #region 加工人员列表操作
    protected void btnSelectAll2_Click(object sender, EventArgs e)
    {
        ClearMessage();

        TemplatedColumn temCell = (TemplatedColumn)wgEmployee.Columns.FromKey("ckSelect");

        for (int i = 0; i < temCell.CellItems.Count; i++)
        {
            Infragistics.WebUI.UltraWebGrid.CellItem cellItem = (Infragistics.WebUI.UltraWebGrid.CellItem)temCell.CellItems[i];
            CheckBox ckSelect = (CheckBox)cellItem.FindControl("ckSelect");

            ckSelect.Checked = true;
        }
    }

    protected void btnReverseSelect2_Click(object sender, EventArgs e)
    {
        ClearMessage();

        TemplatedColumn temCell = (TemplatedColumn)wgEmployee.Columns.FromKey("ckSelect");

        for (int i = 0; i < temCell.CellItems.Count; i++)
        {
            Infragistics.WebUI.UltraWebGrid.CellItem cellItem = (Infragistics.WebUI.UltraWebGrid.CellItem)temCell.CellItems[i];
            CheckBox ckSelect = (CheckBox)cellItem.FindControl("ckSelect");

            ckSelect.Checked = !ckSelect.Checked;
        }
    }
    #endregion

    #region 产品序号列表操作
    protected void btnSelectAll_Click(object sender, EventArgs e)
    {
        ClearMessage();

        TemplatedColumn temCell = (TemplatedColumn)wgProductNo.Columns.FromKey("ckSelect");

        for (int i = 0; i < temCell.CellItems.Count; i++)
        {
            Infragistics.WebUI.UltraWebGrid.CellItem cellItem = (Infragistics.WebUI.UltraWebGrid.CellItem)temCell.CellItems[i];
            CheckBox ckSelect = (CheckBox)cellItem.FindControl("ckSelect");

            ckSelect.Checked = true;
        }
    }

    protected void btnReverseSelect_Click(object sender, EventArgs e)
    {
        ClearMessage();

        TemplatedColumn temCell = (TemplatedColumn)wgProductNo.Columns.FromKey("ckSelect");

        for (int i = 0; i < temCell.CellItems.Count; i++)
        {
            Infragistics.WebUI.UltraWebGrid.CellItem cellItem = (Infragistics.WebUI.UltraWebGrid.CellItem)temCell.CellItems[i];
            CheckBox ckSelect = (CheckBox)cellItem.FindControl("ckSelect");

            ckSelect.Checked = !ckSelect.Checked;
        }
    }
    #endregion

    /// <summary>
    /// 数据采集
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnDataCol_Click(object sender, EventArgs e)
    {
        ClearMessage();

        try
        {
            if (txtDispContainerName.Text==null || txtDispContainerName.Text == "")
            {
                DisplayMessage("请选择批次信息！", false);
                return;
            }

            Dictionary<string, string> popupData = new Dictionary<string, string>();
            //工作令号
            popupData.Add("ProcessNo", txtDispProcessNo.Text);

            //作业令号
            popupData.Add("OprNo", txtDispOprNo.Text);

            //批次号
            popupData.Add("ContainerName", txtDispContainerName.Text);

            //生产任务
            popupData.Add("MfgorderName", txtMfgorderName.Text);

            //图号
            popupData.Add("ProductName", txtDispProductName.Text);

            //名称
            popupData.Add("Description", txtDispDescription.Text);

            //批次数量
            popupData.Add("ConQty", txtContaiernQty.Text);

            //计划开始时间
            popupData.Add("StartTime", txtEndTime.Text);

            //计划结束时间
            popupData.Add("EndTime", txtStartTime.Text);

            //工序
            popupData.Add("SpecDisName", txtDispSpecName.Text);

            //跟踪卡ID
            popupData.Add("ContainerID", txtDispContainerID.Text);

            //图号ID
            popupData.Add("ProductID", txtProductID.Text);

            //工艺规程ID
            popupData.Add("WorkflowID", txtDispWorkflowID.Text);

            //工序ID
            popupData.Add("SpecID", txtDispSpecID.Text);


            Session["PopupData"] = popupData; 
            
            string strScript = "<script>openPopUpForm()</script>";
            Infragistics.WebUI.Shared.CallBackManager.AddScriptBlock(Page, WebAsyncRefreshPanel1, strScript);
        }
        catch (Exception Ex)
        {
            DisplayMessage(Ex.Message, false);
        }

    }

    /// <summary>
    /// 工艺文档查看
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Button1_Click(object sender, EventArgs e)
    {
        ClearMessage();

        UltraGridRow uldr = ItemGrid.DisplayLayout.ActiveRow;
        if (uldr == null)
        {
            DisplayMessage("请选择批次记录", false);
            //Infragistics.WebUI.Shared.CallBackManager.AddScriptBlock(Page, WebAsyncRefreshPanel1, "<script>alert('请选择批次记录')</script>");
            return;
        }

        DataTable poupDt = new DataTable();
        poupDt.Columns.Add("ProductID");
        poupDt.Columns.Add("WorkflowID");
        DataRow newRow = poupDt.NewRow();
        newRow["ProductID"] = uldr.Cells.FromKey("ProductID").Text;
        newRow["WorkflowID"] = uldr.Cells.FromKey("WorkflowID").Text;
        poupDt.Columns.Add("ContainerID"); poupDt.Columns.Add("ContainerName");
        newRow["ContainerID"] = uldr.Cells.FromKey("ContainerID").Text;
        newRow["ContainerName"] = uldr.Cells.FromKey("ContainerName").Text;
        poupDt.Rows.Add(newRow);
        Session.Add("ProcessDocument", poupDt);
        //string strScript = string.Empty;

        //strScript = "<script>window.showModalDialog('Custom/bwCommonPage/uMESDocumentViewPopupForm.aspx', '', 'dialogWidth: 700px; dialogHeight: 600px; status = no; center: Yes; resizable: NO; ')</script>";
        //Infragistics.WebUI.Shared.CallBackManager.AddScriptBlock(Page, WebAsyncRefreshPanel1, strScript);

        var page = "Custom/bwCommonPage/uMESDocumentViewPopupForm.aspx";
        var script = String.Format("<script>OpenPopupWindow(false,'{0}','dialogWidth={1}px;dialogHeight={2}px;status=0');</script>", page, 700, 600);
        Infragistics.WebUI.Shared.CallBackManager.AddScriptBlock(Page, WebAsyncRefreshPanel1, script);
    }
    /// <summary>
    /// 查询
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        try
        {
            hdScanCon.Value = string.Empty;
            QueryData(upageTurning.CurrentPageIndex);
        }
        catch (Exception ex)
        {
            DisplayMessage(ex.Message, false);
        }
    }
}